{
open Ast
exception LexicalError of string
}

let digit = ['0'-'9']
let alpha = ['a'-'z' 'A'-'Z']
let ident = alpha (alpha | digit | '_')*

rule token = parse
  | [' ' '\t' '\n'] { token lexbuf }  (* 跳过空白 *)
  
  (* 注释 *)
  | "//" [^'\n']* '\n' { token lexbuf }
  | "/*" { comment lexbuf }
  
  (* 关键字 *)
  | "int" { T_TY TInt }
  | "void" { T_TY TVoid }
  | "if" { T_IF }
  | "else" { T_ELSE }
  | "while" { T_WHILE }
  | "break" { T_BREAK }
  | "continue" { T_CONTINUE }
  | "return" { T_RETURN }
  
  (* 运算符 *)
  | '+' { T_ADD }
  | '-' { T_SUB } 
  | '*' { T_MUL }
  | '/' { T_DIV }
  | '%' { T_MOD }
  | '!' { T_UNARY UNot }
  | '=' { T_ASSIGN }
  | "==" { T_EQ }
  | "!=" { T_NE }
  | "<=" { T_LE }
  | ">=" { T_GE }
  | '<' { T_LT }
  | '>' { T_GT }
  | "&&" { T_AND }
  | "||" { T_OR }
  
  (* 分隔符 *)
  | '(' { T_LPAREN }
  | ')' { T_RPAREN }
  | '{' { T_LBRACE }
  | '}' { T_RBRACE }
  | ';' { T_SEMI }
  | ',' { T_COMMA }
  
  (* 标识符和整数 *)
  | digit+ as num { T_INT (int_of_string num) }
  | ident as id { T_ID id }
  
  | eof { T_EOF }
  | _ { raise (LexicalError ("非法字符: " ^ Lexing.lexeme lexbuf)) }

and comment = parse
  | "*/" { token lexbuf }
  | _ { comment lexbuf }
  | eof { raise (LexicalError "未闭合的多行注释") }